#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "cJSON/cJSON.h"
#include "cgic.h"

int cgiMain()
{
    char url_address[100];
    char url_type[100];

    int fd = open("/etc/my_fifo", O_WRONLY);
	if(fd < 0)
	{
		perror("open error");
		return 0;
	}

    FILE *file = fopen("/demo/bin/boa/www/cjson_dir/network_detail.json", "r");
    if (file == NULL)
    {
        perror("打开文件时出错");
        return EXIT_FAILURE;
    }
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *data = (char *)malloc(length + 1);
    fread(data, 1, length, file);
    data[length] = '\0';
    cJSON *json = cJSON_Parse(data);
    if (json == NULL)
    {
        printf("json parse error....\n");
    }

    cgiHeaderContentType("text/html");
    fprintf(cgiOut, "<HTML><HEAD>\n");
    fprintf(cgiOut, "<TITLE>Save Address</TITLE></HEAD>\n");
    fprintf(cgiOut, "<BODY>");
    cgiFormString("url_address", url_address, 100);
    cgiFormString("url_type", url_type, 100);

    if (url_address != NULL)
    {
        fprintf(cgiOut, "<H1>%s</H1>", url_address);
        cJSON_ReplaceItemInObject(json, "url_address", cJSON_CreateString(url_address));
    }
    else
    {
        fprintf(cgiOut, "<H1>NULL URL_ADDRESS</H1>");
    }

    if (url_type != NULL)
    {
        fprintf(cgiOut, "<H1>%s</H1>", url_type);
        cJSON_ReplaceItemInObject(json, "url_type", cJSON_CreateString(url_type));
    }
    else
    {
        fprintf(cgiOut, "<H1>NULL URL_TYPE</H1>");
    }

    fprintf(cgiOut, "<a href=\"/cgi-bin/index_button.cgi\">To Main Page</a>\n");
    fprintf(cgiOut, "</BODY>\n");
    fprintf(cgiOut, "</HTML>\n");

    char *new_json_str = cJSON_PrintUnformatted(json);
    // 将新的JSON字符串写入文件
    FILE *new_file = fopen("/demo/bin/boa/www/cjson_dir/network_detail.json", "w");
    if (new_file == NULL)
    {
        printf("Can not Create New File....\n");
        return -1;
    }
    fputs(new_json_str, new_file);

    write(fd, "3", strlen("3"));
    close(fd);

    

    //fprintf(cgiOut, "<script type=text/javascript>window.location= 'index_button.cgi'></script>");

    return 0;
}
